package com.maint.m

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import com.maint.m.StreamManager.StreamCallback
import com.maint.m.StreamUtils.DEFAULT_RTMP_URL
import com.maint.m.StreamUtils.showStreamMessage
import com.pedro.rtplibrary.view.OpenGlView
import okio.ByteString
import org.json.JSONObject

class StreamingActivity : BaseActivity(), StreamCallback, WebSocketMessageListener {

    private lateinit var openGlView: OpenGlView
    private lateinit var streamStatus: TextView
    private lateinit var startStreamBtn: Button
    private lateinit var stopStreamBtn: Button

    private var streamManager: StreamManager? = null
    private var isStreaming = false

    private var isStreamingVisible = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_streaming)

        // 设置标题栏文字
        setToolbarTitle("识别操作票")

        // 初始化视图
        initViews()

        // 初始化流媒体管理器
        streamManager = StreamManager(this, openGlView)
        streamManager?.setStreamCallback(this)

        // 注册 WebSocket 消息监听器
        WebSocketManager.getInstance().registerMessageListener(this)

        val jsonMessage = "{\"business\":1}"
        Log.i("WebSocket", "推流开始前发送消息：$jsonMessage")

        // 使用基类提供的便捷方法发送消息
        sendWebSocketMessage(jsonMessage, showToast = true)

    }

    private fun initViews() {
        openGlView = findViewById(R.id.openGlView)
        streamStatus = findViewById(R.id.streamStatus)
        startStreamBtn = findViewById(R.id.startStreamBtn)
        stopStreamBtn = findViewById(R.id.stopStreamBtn)

        // 设置按钮点击事件
        startStreamBtn.setOnClickListener {
            startStreaming()
        }

        stopStreamBtn.setOnClickListener {
            stopStreaming()
        }

        // 初始状态下停止按钮不可用
        stopStreamBtn.isEnabled = false

        isStreamingVisible = true
    }

    private val webSocketHandler = object : SimpleWebSocketHandler {
        override fun onMessageReceived(type: WebSocketMessageType, message: String) {
            Log.i("WebSocket-Streaming", "收到消息: $message")

            // 处理收到的消息
            try {
                // 解析JSON消息
                val jsonObject = org.json.JSONObject(message)
                val business = jsonObject.getInt("business")
                val data = jsonObject.optString("data", "")

                // 检查是否是推流响应消息 {"business": 0, "data": "ok"}
                if (isStreamingVisible && business == 0 && data == "ok") {
                    Log.i("WebSocket", "收到推流响应消息: $message，当前Activity可见，执行跳转")
                    Toast.makeText(this@StreamingActivity, "准备完毕，可以开始识别操作票", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                finish()
            }
        }

        override fun onConnectionChanged(connected: Boolean) {
            val status = if (connected) "已连接" else "未连接"
            Log.d("WebSocket", "连接状态: $status")
        }

        override fun onError(errorMsg: String) {
            Log.e("WebSocket", "错误: $errorMsg")
        }
    }

    private fun startStreaming() {
        if (!isStreaming) {
            streamManager?.startStreaming(DEFAULT_RTMP_URL)
        }
    }

    private fun stopStreaming() {
        if (isStreaming) {
            streamManager?.stopStreaming()
        }
    }

    override fun onStreamStarted() {
        runOnUiThread {
            streamStatus.text = "推流中"
            isStreaming = true
            startStreamBtn.isEnabled = false
            stopStreamBtn.isEnabled = true
            showStreamMessage(this, "开始推流")
        }
    }

    override fun onStreamStopped() {
        runOnUiThread {
            streamStatus.text = "已停止"
            isStreaming = false
            startStreamBtn.isEnabled = true
            stopStreamBtn.isEnabled = false
            showStreamMessage(this, "推流已停止")
        }
    }

    override fun onConnectionStarted() {
        runOnUiThread {
            streamStatus.text = "连接中..."
        }
    }

    override fun onConnectionSuccess() {
        runOnUiThread {
            streamStatus.text = "已连接"
            showStreamMessage(this, "RTMP连接成功")
        }
    }

    override fun onConnectionFailed(reason: String) {
        runOnUiThread {
            streamStatus.text = "连接失败"
            isStreaming = false
            startStreamBtn.isEnabled = true
            stopStreamBtn.isEnabled = false
            showStreamMessage(this, "RTMP连接失败: $reason")
        }
    }

    override fun onDisconnected() {
        runOnUiThread {
            streamStatus.text = "已断开"
            isStreaming = false
            startStreamBtn.isEnabled = true
            stopStreamBtn.isEnabled = false
            showStreamMessage(this, "已断开连接")
        }
    }

    override fun onStreamStartError(message: String) {
        runOnUiThread {
            streamStatus.text = "启动失败"
            isStreaming = false
            startStreamBtn.isEnabled = true
            stopStreamBtn.isEnabled = false
            showStreamMessage(this, "推流启动错误: $message")
        }
    }

    override fun onStreamPrepareFailed() {
        runOnUiThread {
            streamStatus.text = "准备失败"
            isStreaming = false
            startStreamBtn.isEnabled = true
            stopStreamBtn.isEnabled = false
            showStreamMessage(this, "推流准备失败")
        }
    }

    override fun onPermissionDenied() {
        runOnUiThread {
            showStreamMessage(this, "权限被拒绝，请授予摄像头和麦克风权限")
        }
    }

    override fun onSurfaceReady() {
        Log.d("StreamingActivity", "Surface已准备就绪")
    }

    override fun onAuthError() {
        runOnUiThread {
            showStreamMessage(this, "认证错误")
        }
    }

    override fun onAuthSuccess() {
        runOnUiThread {
            showStreamMessage(this, "认证成功")
        }
    }

    override fun onMessageReceived(message: String) {
        // 在UI线程中显示接收到的消息
        runOnUiThread {

            try {
                Toast.makeText(this, "收到消息: $message", Toast.LENGTH_LONG).show()
                // 解析后端返回的 JSON 消息
                val jsonObject = JSONObject(message)
                val business = jsonObject.getInt("business")
                val data = jsonObject.getString("data")

                if (business == 11) {
                    if (isStreaming) {
                        streamManager?.stopStreaming()
                    }
                    // 处理工单更新消息
                    val intent = Intent(this@StreamingActivity, TicketConfirmationActivity::class.java)
                    intent.putExtra("websocket_data", data)
                    intent.putExtra("source", "streaming")
                    startActivity(intent)
                    finish()
                }
            } catch (e: Exception) {
                Log.e("WebSocket", "解析消息失败: ${e.message}")
            }
        }
    }

    override fun onBinaryMessageReceived(bytes: ByteString) {
        // 二进制消息处理
        Log.d("WebSocket", "收到二进制消息，长度: ${bytes.size}")
    }

    override fun onConnectionOpened() {
        Log.d("WebSocket", "连接已打开")
    }

    override fun onConnectionFailed(t: Throwable) {
        Log.e("WebSocket", "连接失败: ${t.message}", t)
    }

    override fun onConnectionClosed(code: Int, reason: String) {
        Log.d("WebSocket", "连接已关闭: $code, $reason")
    }

    override fun onResume() {
        super.onResume()

        WebSocketService.getInstance().registerHandler(webSocketHandler, this)
    }

    override fun onDestroy() {
        super.onDestroy()

        streamManager?.onDestroy()

        isStreamingVisible = false

        // 确保移除监听器
        WebSocketService.getInstance().unregisterHandler(webSocketHandler)
    }
}